package com.ray.controller.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.utils.FileExportUtil;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.ray.log.WebLog;
import com.ray.model.Report;
import com.ray.util.Ret;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController extends BaseController {

    /**
     * @note 获取报表树形结构
     * @time 2024年03月25日 13:56:25
     * @author Ray
     */
    @RequestMapping("getReportList")
    @WebLog(description = "获取报表树形结构")
    public Ret getReportList() {
        List<Record> list = Db.use(base).find("select * from report where parent_id = 0");
        list = tree(list);
        return Ret.ok("msg", "成功").setJson("list", list);
    }

    public List<Record> tree(List<Record> trees) {
        for (int i = 0; i < trees.size(); i++) {
            List<Record> temp = Db.use(base).find("select * from report where parent_id = " + trees.get(i).getInt("id"));
            tree(temp);
            trees.get(i).set("children", temp);
        }
        return trees;
    }

    /**
     * @note 修改报表名称
     * @time 2024年03月25日 15:37:19
     * @author Ray
     */
    @RequestMapping("updateName")
    @WebLog(description = "修改报表名称")
    public Ret updateName(@RequestBody Report model) {
        model.update();
        return Ret.ok("msg", "修改成功");
    }

    /**
     * @note 新增分类
     * @time 2024年03月25日 15:38:16
     * @author Ray
     */
    @RequestMapping("add")
    @WebLog(description = "新增分类")
    public Ret add(@RequestBody Report model) {
        model.setRegion(getSessionUserRegion());
        model.setParentId(1);
        model.save();
        return Ret.ok("msg", "新增分类成功");
    }

    /**
     * @note 新增报表
     * @time 2024年03月25日 15:39:15
     * @author Ray
     */
    @RequestMapping("addReport")
    @WebLog(description = "新增报表")
    public Ret addReport(@RequestBody Report model) {
        model.setRegion(getSessionUserRegion());
        model.save();
        return Ret.ok("msg", "新增报表成功");
    }

    /**
     * @note 保存报表
     * @time 2024年03月25日 15:39:49
     * @author Ray
     */
    @RequestMapping("save")
    @WebLog(description = "保存报表")
    public Ret save(@RequestBody Report model) {
        model.update();
        return Ret.ok("msg", "保存成功");
    }

    /**
     * @note 删除报表
     * @time 2024年03月25日 15:40:34
     * @author Ray
     */
    @RequestMapping("delReport")
    @WebLog(description = "删除报表")
    public Ret delReport(@RequestBody Report model) {
        model.delete();
        return Ret.ok("msg", "删除报表成功");
    }

    /**
     * @note 获取预览报表列
     * @time 2024年03月25日 15:46:46
     * @author Ray
     */
    @RequestMapping("getColumns")
    @WebLog(description = "获取预览报表列")
    public Ret getColumns(int id) {
        Report model = Report.dao.findById(id);
        return Ret.ok("msg", "成功").setJson("report", model);
    }

    /**
     * @note
     * @time 2024年03月25日 15:51:14
     * @author Ray
     */
    @RequestMapping("getList")
    @WebLog(description = "getList")
    public Ret getList(@RequestBody JSONObject param) {
        Report model = Report.dao.findById(param.getIntValue("id"));
        String sql = model.getRSql();
        JSONArray params = param.getJSONArray("params");
        if (params != null) {
            for (int i = 1; i <= params.size(); i++) {
                sql = sql.replace("{" + i + "}", params.getString(i - 1));
            }
        }
        sql = sql.replaceAll("\\{\\d+\\}", "");
        List<Record> list = Db.find(sql);
        return Ret.ok("msg", "成功").setJson("list", list);
    }

    /**
     * @note 报表数据导出功能
     * @time 2024年03月25日 16:01:50
     * @author Ray
     */
    @RequestMapping("reportExport")
    @WebLog(description = "报表数据导出")
    public Ret reportExport(@RequestBody JSONObject param) throws IOException {
        Report report = Report.dao.findById(param.getIntValue("id"));
        String sql = report.getRSql();
        JSONArray params = param.getJSONArray("params");
        if (params != null) {
            for (int i = 1; i <= params.size(); i++) {
                sql = sql.replace("{" + i + "}", params.getString(i - 1));
            }
        }
        sql = sql.replaceAll("\\{\\d+\\}", "");
        List<Record> list = Db.find(sql);
        //获取数据
        //初始化表头
        Map<String, String> headerMap = new LinkedHashMap<>();
        String[] fieldsArray = report.getRColumn().split(",");
        for (int i = 0; i < fieldsArray.length; i++) {
            headerMap.put(fieldsArray[i], fieldsArray[i]);
        }
        List<Map> dataMapList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> temp = list.get(i).getColumns();
            dataMapList.add(temp);
        }
        List<String> titles = new ArrayList(headerMap.values());
        List<String> orders = new ArrayList(headerMap.keySet());
        Workbook workbook = DefaultExcelBuilder.of(Map.class)
                .sheetName("导出")
                .titles(titles)
                .widths(10, 20)
                .fieldDisplayOrder(orders)
                .fixedTitles()
                .build(dataMapList);
        String filename = report.getName() + "_" + new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(new Date()) + ".xlsx";
        File file = new File(domin_path + "/export/" + filename);
        FileExportUtil.export(workbook, file);
        return Ret.ok("msg", "成功").set("url", domin_url + "/export/" + filename);
    }
}
